import axios from 'axios'
import store from "../store"
import {paramDeal} from "../utils/util"
import {weakAlert} from "../utils/dialog";


//创建axios实例
let httpRequest = axios.create({
  timeout:10000,
  headers:{'ContentType':'application/json'},
})
/*
* 请求配置
* */
httpRequest.interceptors.request.use(config=>{
  //请求头上带上token
  config.headers.authorization=store.getters.token;
  return config;
},error => {
  return Promise.reject(error.response)
})

/*
* 响应拦截
* */
httpRequest.interceptors.response.use(config=>{
  return config;
},error => {
  return Promise.reject(error.response)
});

export default {
  /*
  * 下载文件
  * @param url:请求地址;
  * data:请求参数;
  * type:接收文件类型可在响应头中查找
  * */
  DownLoad(url,data,type){
    return new Promise((resolve,reject) =>{
      httpRequest.post(url, data,{ responseType: 'arraybuffer' }).then(res => {
        const blob = new Blob([res.data], { type: type||'application/vnd.ms-excel;'})
        const a = document.createElement('a')
        // 生成文件路径
        let href = window.URL.createObjectURL(blob)
        a.href = href
        let _fileName = res.headers['content-disposition'].split(';')[1].split('=')[1]
        // 文件名中有中文 则对文件名进行转码
        a.download = decodeURIComponent(_fileName)
        // 利用a标签做下载
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        window.URL.revokeObjectURL(href);
        resolve();
      }).catch(err=>{
        reject(err);
      })
    })
  },
  /**
   * @author 张天丰
   * @date 2020/8/21
   * @Description：axios POST请求
   * @param：url：请求地址 data：请求参数
   * @return：Promise
   */
  HttpPost: function (url, data) {
    if(data){
      return new Promise((resolve,reject) => {
        httpRequest.post(url, data).then(response => {
          resolve(paramDeal.resData(response));
        }).catch(err=>{
          weakAlert('请求失败，请稍后再试！'+err,'error');
          reject(err)
        })
      })
    }else{
      return new Promise((resolve,reject) => {
        httpRequest.post(url).then(response => {
          resolve(paramDeal.resData(response));
        }).catch(err=>{
          weakAlert('请求失败，请稍后再试！'+err,'error');
          reject(err)
        })
      })
    }
  },
  /**
   * @author 张天丰
   * @date 2020/8/21
   * @Description：axios GET请求
   * @param：url：请求地址 data：请求参数
   * @return：Promise
   */
  HttpGet: function (url, data) {
    if(data){
      return new Promise((resolve,reject) => {
        httpRequest.get(url, data).then(response => {
          resolve(paramDeal.resData(response));
        }).catch(err=>{
          weakAlert('请求失败，请稍后再试！'+err,'error');
          reject(err)
        })
      })
    }else{
      return new Promise((resolve,reject) => {
        httpRequest.get(url).then(response => {
          resolve(paramDeal.resData(response));
        }).catch(err=>{
          weakAlert('请求失败，请稍后再试！'+err,'error');
          reject(err)
        })
      })
    }
  }
}
